var pay = function(){

    //动态生成省市区三级联动选择
    var address = function(){
       /*
       //循环实例代码
        for(var i=0;i<Area.length;i++){
            console.log(Area[i].name);
            for(var j = 0;j<Area[i].city.length;j++){
                console.log(Area[i].city[j].name);
                for(var k = 0;k<Area[i].city[j].area.length;k++){
                    console.log(Area[i].city[j].area[k]);
                }
            }
        }*/
        //定义空数组去存储被选择的区域
        var province = [];
        var city = [];
        var district = [];

        var proObj="";
        var cityObj="";

        var proIndex = 0;
        var cityIndex = 0;


        //点击的是省
        $('.province').on('click',function(){
            province.length=0;
            city.length=0;
            district.length=0;
            $('.city').html("城市");
            $('.district').html('区县');
            for(var i=0,len=Area.length;i<len;i++){
                province.push(Area[i].name);
            }
            getAddress(province);
            selectAndRemove($('.province'));
        });

        //点击的是市
        $('.city').on('click',function(){
            city.length=0;
            district.length=0;
            $('.district').html('区县');
            proObj = $('.province').html();
            if(proObj =="省份"){
                messageBox("请先选择省份");
            }else{
                proIndex = getIndex(province,proObj);
                for(var j = 0;j<Area[proIndex].city.length;j++){
                    city.push(Area[proIndex].city[j].name);
                }
                getAddress(city);
                selectAndRemove($('.city'));
            }
        });
        //点击的是区县
        $('.district').on('click',function(){
            district.length=0;
            cityObj = $('.city').html();
            if(cityObj =="城市"){
                messageBox("请先选择城市");
            }else{
                cityIndex = getIndex(city,cityObj);
                for(var k = 0;k<Area[proIndex].city[cityIndex].area.length;k++){
                    district.push(Area[proIndex].city[cityIndex].area[k]);
                }
                getAddress(district);
                selectAndRemove($('.district'));
            }
        });

         function getIndex(arr,obj){
             for(var x=0;x<arr.length;x++){
                 if(arr[x]==obj){
                     return x;
                 }
             }
         }
        function selectAndRemove(container){
            //对列表中的内容进行选择
            $('.address-list').delegate('li','click',function(){
                //点击获得选中的文本内容，然后list消失
                $(container).html($(this).text());
                $('.address-list').remove();
            });
        }

        function getAddress(data){
            //循环遍历json数据显示出选择列表
            $('body').append(getList(data));
            autoSize($('.address-list'));

        //生成选择列表的函数
        function getList(list){
            var str="";
            for(var i=0,len=list.length;i<len;i++){
                str  += "<li>"+list[i]+"</li>";
            }
            var para =  '<div class="am-panel am-panel-secondary address-list"><ul class="am-list am-list-static  ">'+str+'</ul></div>'
            return para;
        }
        }

    };

    //地址列表有大于1的时候，默认地址显示第一个地址，此时将隐藏的地址列表的第一个选中，此后将标识是哪个选中
    var selectAddress = function(){
        //第一次进入默认将第一条选中
        $('.addressList').find('.flex').eq(0).find('.addSelect').removeClass('uncheck-icon').addClass('check-icon');

        //在选择地址的列表页点击'关闭按钮'
        $('.addressList .close-icon').on('click',function(){
            //选择带有选中标识的地址信息添加进页面
            var node = $('.addressList').find('i.addSelect.check-icon');
            console.log(node);
            if(node.length==0){
                messageBox("请先选择一个或者创建一个地址");
            }else{
                var detail = node.parent().next('.addDetail');
                var addressId = detail.attr('data-objectId');
                var name = detail.attr('data-name');
                var phone = detail.attr('data-phone');
                var province = detail.attr('data-province');
                var city = detail.attr('data-city');
                var district = detail.attr('data-district');
                var address = detail.attr('data-address');

                var addressData = {
                    objectId:addressId,
                    name:name,
                    tel:phone,
                    province:province,
                    city:city,
                    district:district,
                    address:address
                };

                createPageAddress(addressData);
                $('.mask').css('display','none');
                $('.addressList').slideUp();
            }

        });


    };

    //显示新增地址弹出窗
    var callNewAddressWindow = function () {
        $('.am-container').delegate('.addNew','click',function(){

            //点击新增的时候，防止修改地址的时候表单中有信息，先进行一个reset
            $('input[name="name"]').val('');
            $('input[name="phone"]').val('');
            $('.province').text("省份");
            $('.city').text("城市");
            $('.district').text("区县");
            $('input[name="address"]').val('');
            $('input[name="postcode"]').val('');

            //改变页头
            $('.addressManage .am-g:nth-child(1)').html('新增收货地址<span class="inline-block close-icon am-fr"></span>');

            //对各种弹出框进行显示和隐藏
            $('.mask').css('display','block');
            $('.delete-address').css('display','none');
            $('.addressList').css('display','none');
            $('.addressManage').slideDown();
        });
    };

    //新增或编辑地址的保存事件(ajax)
    var Address = function(){
        $('.addressManage').delegate('#addressBtn','click',function(){
            var isEdit = $(this).attr('data-isEdit');
            var self = $(this);
            self.attr('disabled','disabled');
            if(isEdit=="false"){
                //此时为新建一个地址

                //获取参数
                var name = $('input[name="name"]').val();
                var phone = $('input[name="phone"]').val();
                var province = $('.province').text();
                var city = $('.city').text();
                var district = $('.district').text();
                var address = $('input[name="address"]').val();
                var postcode = $('input[name="postcode"]').val();

                //检查参数
                if(!name || !phone || !address || province=="省份" || city=="城市" || district=="区县"){
                    messageBox("请完善收货信息");
                    self.removeAttr('disabled');
                    return;
                }

                //信息正确，封装信息
                var data = {
                    name:name,
                    phone:phone,
                    province:province,
                    city:city,
                    district:district,
                    address:address,
                    postcode:postcode
                };

                //发送ajax请求
                $.post('addAddress',data).then(function(msg){
                    if(msg.code==200){
                        var addressData = msg.results;
                        if($('.addressChoose').length==0){
                            // 第一次添加成功的时候，需要把地址填进页面,
                            createPageAddress(addressData);
                        }
                        //添加进去addressList
                        modifyAddList(addressData);
                        //成功后提示并隐藏新加地址框
                        messageBox("新增地址成功");
                        $('.addressManage').css('display','none');
                        $('.addressList').css('display','block');
                        self.removeAttr('disabled');
                    }else if(msg.code == 103){
                        messageBox("您还未登录，请登录后操作");
                        doLogin();
                        self.removeAttr('disabled');
                    }else{
                        messageBox(msg.msg);
                        self.removeAttr('disabled');
                    }
                },function(err){
                    messageBox("新增地址失败");
                    self.removeAttr('disabled');
                });


            }else{
                //此时为编辑地址，与新增地址相比，需要获取所编辑的地址的addressId

                //获取参数
                var addressId = $('#addressId').val();//获得隐藏域所存储的要修改的地址id
                var name_m = $('input[name="name"]').val();
                var phone_m = $('input[name="phone"]').val();
                var province_m = $('.province').text();
                var city_m = $('.city').text();
                var district_m = $('.district').text();
                var address_m = $('input[name="address"]').val();
                var postcode_m = $('input[name="postcode"]').val();

                //检查参数
                if(!addressId || !name_m || !phone_m || !address_m || province_m=="省份" || city_m=="城市" || district_m=="区县"){
                    messageBox("请完善收货信息");
                    self.removeAttr('disabled');
                    return;
                }

                //信息正确，封装信息
                var data_m = {
                    addressId:addressId,
                    name:name_m,
                    phone:phone_m,
                    province:province_m,
                    city:city_m,
                    district:district_m,
                    address:address_m,
                    postcode:postcode_m
                };

                //发送ajax请求
                $.post('editAddress',data_m).then(function(msg){
                    if(msg.code==200){
                        var data = msg.results;
                        messageBox("修改成功");
                         // 修改成功的时候需要动态改变修改后的地址
                        $('div [data-addressinfo='+data_m.addressId+']').remove();
                        modifyAddList(data);

                        //隐藏修改，显示列表
                        $('.addressManage').css('display','none');
                        $('.addressList').css('display','block');
                        self.removeAttr('disabled');
                    }else if(msg.code == 103){
                        messageBox("您还未登录，请登录后操作");
                        doLogin();
                        self.removeAttr('disabled');
                    }else{
                        messageBox(msg.msg);
                        self.removeAttr('disabled');
                    }
                },function(err){
                    messageBox("修改地址失败");
                    self.removeAttr('disabled');
                });
            }


        });
    };

    //在地址列表里选择地址
    var addressChoose = function(){
        $('.am-container').delegate('.addressChoose','click',function(){
            $('.mask').css('display','block');
            $('.addressList').slideDown();
        });
        //选择地址 然后将选择的地址放在页面上
        $('.addressList').delegate('.addDetail','click',function(){
            $(this).prev().find('.addSelect').removeClass('uncheck-icon').addClass('check-icon');
            $(this).parents('.flex').siblings().find('.addSelect').removeClass('check-icon').addClass('uncheck-icon');

            var addressId = $(this).attr('data-addressId');
            var name = $(this).attr('data-name');
            var phone = $(this).attr('data-phone');
            var province = $(this).attr('data-province');
            var city = $(this).attr('data-city');
            var district = $(this).attr('data-district');
            var address = $(this).attr('data-address');
            var data = {
                objectId:addressId,
                name:name,
                tel:phone,
                province:province,
                city:city,
                district:district,
                address:address
            };
            createPageAddress(data);

            //每次选择地址的时候，将获取的addressID存在input隐藏域中
            $('#addressId').val(addressId);

            $('.mask').css('display','none');
            $('.addressList').slideUp();
        })
    };

    //在编辑或者新增页面点击关闭close icon
    var closeAddress = function(){
        $('.addressManage ').on('click','.close-icon',function(){
            $('.mask').css('display','none');
            $('.addressManage').slideUp();
        });
    };

    //编辑地址
    var editAddress = function(){
        $('.addressList').delegate('.edit-icon','click',function (e) {

            //点击编辑按钮时，先获得编辑的数据信息
            var detail = $(this).parent().prev('.addDetail');
            var addressId = detail.attr('data-addressId');
            var name = detail.attr('data-name');
            var phone = detail.attr('data-phone');
            var province = detail.attr('data-province');
            var city = detail.attr('data-city');
            var district = detail.attr('data-district');
            var address = detail.attr('data-address');
            var postcode = detail.attr('data-postcode');

            //每次点击编辑的时候，将所要编辑的地址的addressId存进id为addressId的隐藏域
            $('#addressId').val(addressId);

            //隐藏此弹出框，弹出编辑弹出框，将获得的数据信息放进去
            $('.addressList').css('display','none');
            $('.addressManage .am-g:nth-child(1)').html('编辑收货地址<span class="inline-block close-icon am-fr"></span>');
            $('input[name="name"]').val(name);
            $('input[name="phone"]').val(phone);
            $('.province').text(province);
            $('.city').text(city);
            $('.district').text(district);
            $('input[name="address"]').val(address);
            $('input[name="postcode"]').val(postcode);


            //显示删除按钮，显示修改地址,

            $('.delete-address').css('display','block');
            $('#addressBtn').attr('data-isEdit','true');

            $('.addressManage').css('display','block');
        });
    };

    //删除地址
    var deleteAddress = function(){
        $('.delete-address').click(function(){
            var addressId = $('#addressId').val();
            if(!addressId){
                messageBox("获取地址信息失败");
                return;
            }
            $.post('/delAddress',{addressId:addressId}).then(function (msg) {
                if(msg.code == 200){
                    messageBox("删除成功");
                    $('div[data-addressInfo='+addressId+']').remove();
                    $('.addressManage').css('display','none');
                    $('.addressList').css('display','block');
                }else if(msg.code == 103){
                    messageBox("您还未登录，请登录后操作");
                    doLogin();
                }else{
                    messageBox(msg.message,'alert');
                }
            })
        })
    };

    //将  新增、修改后的地址动态的添加进入地址列表里
    function modifyAddList(data){
        var address = '<div class="am-g am-padding-sm border-bottom-add flex " data-addressinfo ="'+data.objectId+'"'+'><div class="am-u-sm-1"><i class="am-inline-block uncheck-icon addSelect"></i></div>'+
            '<div data-addressId="'+data.objectId+'" ' + 'data-name="'+data.name+'" data-phone="'+data.tel+'" ' +
            'data-province="'+data.province+'" data-city="'+data.city+'" data-district="'+data.district+'" data-address="'+data.address+'" ' +
            'data-postcode="'+data.postcode+'" class="am-u-sm-10 addDetail"><p class="am-margin-0">' + data.name+
            '&nbsp;&nbsp;'+data.tel+'</p><p class="gray-color xs-font am-margin-0"> 收获地址: ' +data.province+data.city+data.district+data.address+
            '</p></div><div class="am-u-sm-1"><i class="am-inline-block edit-icon"></i></div></div>';
        $('.addressList .am-g:first').after(address);
    }

    //页面显示形成地址
    function createPageAddress(addressData){
        var addressHtml ='';
        if(addressData){
            $('.addNewAddress').remove();
            addressHtml='<div class="am-g flex address-box addressChoose" data-address="'+addressData.objectId+'"><div class="am-u-sm-1"><i class="am-inline-block address-icon"></i></div>'+
                '<div class="am-u-sm-10" ><p class="am-margin-bottom-0">收货人&nbsp;:&nbsp;' +addressData.name+
                '<span class="am-fr">' +addressData.tel+
                '</span></p><p class="am-margin-top-0">收货地址&nbsp;:&nbsp;' +addressData.province+addressData.city+addressData.district+addressData.address+
                '</p></div><div class="am-u-sm-1 am-padding-left-0 "><i class="am-inline-block more-icon"></i></div></div>';
        }else{
            addressHtml='<div class="am-g flex address-box addNewAddress"><div class="am-u-sm-11 am-padding-lg">' +
                '<i class="am-inline-block add-new-icon am-margin-right-sm"></i><p class="md-font am-inline-block">新增收货地址</p>'+
                '</div><div class="am-u-sm-1 am-padding-left-0"><i class="am-inline-block more-icon am-fr"></i></div></div>';
        }
        $('.am-container:first').html(addressHtml);
    }


    //生成订单
    var confirmBuy = function () {
        $('#createOrder').on('click', function () {
            var self = $(this);
            //点击后禁用
            self.attr('disabled', 'disabled');

            //取值
            var addressId = $('#addressId').val();
            var selector = $('.cart-shop-pro');
            var remark = $('#reMark').val();
            var products=[];
            selector.each(function(){
                var temp = {};
                temp.product = $(this).attr('data-productId');
                temp.count = $(this).attr('data-count');
                products.push(temp);
            });
            //检查
            if (!addressId || addressId == 'undefined') {
                messageBox("请选择收货地址再提交", 'alert');
                self.removeAttr('disabled');
                return;
            }
            if(!products){
                messageBox("获取商品信息失败", 'alert');
                self.removeAttr('disabled');
                return;
            }

            //开始组织数据
            products = JSON.stringify(products);
            var data = {
                addressId:addressId,
                products:products,
                remark:remark
            };

            $.post('/createOrder', data).then(function (msg) {
                if(msg.code==200){
                    var info = msg.results;
                    window.location.href="/payment?info="+info;
                }else if(msg.code == 103){
                    messageBox("您还未登录，请登录后操作");
                    doLogin();
                }else{
                    messageBox("提交订单失败", 'alert');
                }
                self.removeAttr('disabled');
            }, function (err) {
                messageBox(err, 'alert');
                self.removeAttr('disabled');
            });


        });
    };

    return{
        init:function(){
            address();
            selectAddress();
            callNewAddressWindow();
            Address();
            addressChoose();
            closeAddress();
            editAddress();
            deleteAddress();
            confirmBuy();
        }
    }
}();
